package com.wframe.project.jnd.wx.filter;

import com.wframe.project.jnd.util.ServletUtils;
import org.apache.commons.lang.StringUtils;
import org.glassfish.jersey.server.internal.monitoring.jmx.ResourcesMBeanGroup;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Source;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.xml.transform.Source;
import java.io.IOException;
import java.util.*;

/**
 * Created by Administrator on 2017/5/4.
 */
@Component("deviceRouteFilter")
public class DeviceRouteFilter implements Filter {

    private static Map<String, JumpUri> routeRules = new HashMap<String, JumpUri>();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        if (ServletUtils.isMobile(request)) {
            JumpUri jumpUri = DeviceRouteFilter.routeRules.get(requestURI);
            if (jumpUri != null) {
                String resolveUri = jumpUri.resolveUri(servletRequest.getParameterMap());
                if (StringUtils.isNotEmpty(resolveUri)) {
                    String url = ServletUtils.buildRequestUrlPrefix(request) + resolveUri;
                    response.sendRedirect(url);
                    return;
                }
            }
        }
        chain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String[] routeRuleArray = StringUtils.trimToEmpty(filterConfig.getInitParameter("routeRule")).split(",");
        for (int i = 0; i < routeRuleArray.length; i++) {
            String routeRuleItem = routeRuleArray[i];
            String[] routeRuleConfig = StringUtils.trimToEmpty(routeRuleItem).split("\\|");
            if (routeRuleConfig.length >= 2) {
                String sourceUriReg = StringUtils.trimToEmpty(routeRuleConfig[0]);
                String jumpUriReg = StringUtils.trimToEmpty(routeRuleConfig[1]);
                if (StringUtils.isNotEmpty(sourceUriReg) && StringUtils.isNotEmpty(jumpUriReg)) {
                    routeRules.put(sourceUriReg, new JumpUri(jumpUriReg));
                }
            }
        }
    }

    @Override
    public void destroy() {
    }

    private static class JumpUri {

        private static final String WRAP = "\\{\\w+\\}";

        private String jumpUriReg;

        private String[] phrase;

        public JumpUri(String jumpUriReg) {
            this.jumpUriReg = jumpUriReg;
            List<String> phraseList = new ArrayList<String>();
            Pattern pattern = Pattern.compile(WRAP);
            Matcher matcher = pattern.matcher(jumpUriReg);
            int preSourceStart = 0;
            int preSourceEnd = -1;
            while (matcher.find()) {
                String group = matcher.group();
                if (matcher.start() != preSourceStart) {
                    preSourceEnd = matcher.start();
                    String preSource = null;
                    if (preSourceEnd > preSourceStart && preSourceStart >= 0) {
                        preSource = jumpUriReg.substring(preSourceStart, preSourceEnd);
                    }
                    if (preSource != null) {
                        phraseList.add(preSource);
                    }
                }
                phraseList.add(group);
                preSourceStart = matcher.end();
            }
            if (preSourceStart == 0 && preSourceEnd == -1) {
                phraseList.add(jumpUriReg);
            } else {
                phraseList.add(jumpUriReg.substring(preSourceStart));
            }
            phrase = new String[phraseList.size()];
            phrase = phraseList.toArray(phrase);
        }

        public String getJumpUriReg() {
            return jumpUriReg;
        }

        public String resolveUri(Map<String, String[]> paras) {
            StringBuffer complete = new StringBuffer();
            for (int i = 0; i < phrase.length; i++) {
                String phr = phrase[i];
                if (phr.matches("^" + WRAP + "$")) {
                    String paraKey = phr.substring(1, phr.length() - 1);
                    String[] vals = paras.get(paraKey);
                    String val = (vals != null && vals.length > 0) ? vals[0].toString() : null;
                    if (StringUtils.isNotEmpty(val)) {
                        complete.append(val);
                    } else {
                        //未找到参数则整个URL返回空
                        return null;
                    }
                } else {
                    complete.append(phr);
                }
            }
            return complete.toString();
        }

    }

}
